package com.mm.cloth.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.mm.cloth.R;
import com.mm.cloth.view.MaskDrawingView;

import java.io.ByteArrayOutputStream;

public class MaskDrawingActivity extends AppCompatActivity {
    private static final String TAG = "MaskDrawingActivity";
    public static final String EXTRA_ORIGINAL_IMAGE_URI = "original_image_uri";
    public static final String EXTRA_MASK_BITMAP = "mask_bitmap";
    public static final String EXTRA_EXISTING_MASK = "existing_mask";
    public static final int RESULT_MASK_CREATED = RESULT_FIRST_USER + 1;
    
    private MaskDrawingView maskDrawingView;
    private Button btnConfirm;
    private Button btnClear;
    private Button btnCancel;
    private SeekBar seekBarBrushSize;
    private TextView tvBrushSize;
    private ImageButton btnUndo;
    private ImageButton btnRedo;
    
    private Bitmap originalBitmap;
    private String originalImageUri;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mask_drawing);
        
        initViews();
        loadOriginalImage();
        loadExistingMask();
        setupClickListeners();
        setupBrushSizeControl();
    }
    
    private void initViews() {
        maskDrawingView = findViewById(R.id.maskDrawingView);
        btnConfirm = findViewById(R.id.btnConfirm);
        btnClear = findViewById(R.id.btnClear);
        btnCancel = findViewById(R.id.btnCancel);
        seekBarBrushSize = findViewById(R.id.seekBarBrushSize);
        tvBrushSize = findViewById(R.id.tvBrushSize);
        btnUndo = findViewById(R.id.btnUndo);
        btnRedo = findViewById(R.id.btnRedo);
    }
    
    private void loadOriginalImage() {
        originalImageUri = getIntent().getStringExtra(EXTRA_ORIGINAL_IMAGE_URI);
        if (originalImageUri != null) {
            try {
                Uri imageUri = Uri.parse(originalImageUri);
                originalBitmap = BitmapFactory.decodeStream(
                    getContentResolver().openInputStream(imageUri));
                
                if (originalBitmap != null) {
                    maskDrawingView.setOriginalBitmap(originalBitmap);
                    Log.d(TAG, "原图加载成功: " + originalBitmap.getWidth() + "x" + originalBitmap.getHeight());
                } else {
                    Toast.makeText(this, "图片加载失败", Toast.LENGTH_SHORT).show();
                    finish();
                }
            } catch (Exception e) {
                Log.e(TAG, "加载原图失败: " + e.getMessage());
                Toast.makeText(this, "图片加载失败", Toast.LENGTH_SHORT).show();
                finish();
            }
        } else {
            Toast.makeText(this, "未找到原图", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void loadExistingMask() {
        byte[] existingMaskBytes = getIntent().getByteArrayExtra(EXTRA_EXISTING_MASK);
        if (existingMaskBytes != null) {
            try {
                Bitmap existingMask = BitmapFactory.decodeByteArray(existingMaskBytes, 0, existingMaskBytes.length);
                if (existingMask != null) {
                    maskDrawingView.setMaskBitmap(existingMask);
                    Log.d(TAG, "现有遮罩加载成功: " + existingMask.getWidth() + "x" + existingMask.getHeight());
                }
            } catch (Exception e) {
                Log.e(TAG, "加载现有遮罩失败: " + e.getMessage());
            }
        }
    }
    
    private void setupClickListeners() {
        // 确认按钮 - 返回绘制的遮罩
        btnConfirm.setOnClickListener(v -> {
            if (maskDrawingView.hasMask()) {
                Bitmap maskBitmap = maskDrawingView.getMaskBitmap();
                if (maskBitmap != null) {
                    returnMaskResult(maskBitmap);
                } else {
                    Toast.makeText(this, "获取遮罩失败", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, "请先绘制遮罩区域", Toast.LENGTH_SHORT).show();
            }
        });
        
        // 清除按钮
        btnClear.setOnClickListener(v -> {
            maskDrawingView.clearMask();
            Toast.makeText(this, "遮罩已清除", Toast.LENGTH_SHORT).show();
        });
        
        // 取消按钮
        btnCancel.setOnClickListener(v -> {
            setResult(RESULT_CANCELED);
            finish();
        });
        
        // 撤销按钮
        btnUndo.setOnClickListener(v -> {
            maskDrawingView.undo();
        });
        
        // 重做按钮
        btnRedo.setOnClickListener(v -> {
            maskDrawingView.redo();
        });
        
        // 返回按钮
        findViewById(R.id.btnBack).setOnClickListener(v -> {
            setResult(RESULT_CANCELED);
            finish();
        });
    }
    
    private void setupBrushSizeControl() {
        // 设置画笔大小控制
        seekBarBrushSize.setMax(50);
        seekBarBrushSize.setProgress(20); // 默认20px
        tvBrushSize.setText("20px");
        
        seekBarBrushSize.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    int brushSize = Math.max(5, progress); // 最小5px
                    maskDrawingView.setBrushSize(brushSize);
                    tvBrushSize.setText(brushSize + "px");
                }
            }
            
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}
            
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
    }
    
    private void returnMaskResult(Bitmap maskBitmap) {
        try {
            // 将Bitmap转换为字节数组
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            maskBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();
            
            Intent resultIntent = new Intent();
            resultIntent.putExtra(EXTRA_MASK_BITMAP, byteArray);
            setResult(RESULT_MASK_CREATED, resultIntent);
            
            Toast.makeText(this, "遮罩绘制完成", Toast.LENGTH_SHORT).show();
            finish();
            
        } catch (Exception e) {
            Log.e(TAG, "返回遮罩结果失败: " + e.getMessage());
            Toast.makeText(this, "保存遮罩失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    @Override
    public void onBackPressed() {
        if (maskDrawingView.hasMask()) {
            // 如果有绘制内容，询问是否保存
            new androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("您绘制的遮罩尚未保存，是否要保存？")
                .setPositiveButton("保存", (dialog, which) -> {
                    if (maskDrawingView.hasMask()) {
                        Bitmap maskBitmap = maskDrawingView.getMaskBitmap();
                        if (maskBitmap != null) {
                            returnMaskResult(maskBitmap);
                        } else {
                            super.onBackPressed();
                        }
                    } else {
                        super.onBackPressed();
                    }
                })
                .setNegativeButton("不保存", (dialog, which) -> super.onBackPressed())
                .setNeutralButton("取消", null)
                .show();
        } else {
            super.onBackPressed();
        }
    }
}
